//
//  CreatorInfoViewController.m
//  MovieFans
//
//  Created by 钟义 on 16/1/14.
//  Copyright © 2016年 joker. All rights reserved.
//

#import "CreatorInfoViewController.h"
#import "CreatorTableViewHeader.h"
#import "UINavigationBar+Awesome.h"
#import "AFHTTPSessionManager+Util.h"
#import "UIImageView+WebCache.h"
#import "IntroduceTableViewCell.h"
#import "UIImageView+LBBlurredImage.h"
#import "RelationInfoModel.h"
#import "RelationMovieCell.h"
#import "MovieDetailViewController.h"

@interface CreatorInfoViewController ()<UITableViewDataSource,UITableViewDelegate,ClickRelationInfoCellDelegate>
{
    UIImageView * _iconImageView;
}

@property(nonatomic,strong)UITableView* tableView;
@property(nonatomic,strong)CreatorTableViewHeader* headView;
@property(nonatomic,strong)UIImageView* bigImageView;
@property (nonatomic, strong) UILabel *nameLabel;

@property (nonatomic, strong) NSMutableArray *relationArr;
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * desc;
@property (nonatomic, strong) NSString * picUrl;
@property (nonatomic, assign) int maxPage;
@property (nonatomic, assign) int groupNumber;
@property (nonatomic, assign) int allCount;

@end

@implementation CreatorInfoViewController

-(UITableView*)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

- (NSMutableArray *)relationArr{
    if (!_relationArr) {
        _relationArr = [NSMutableArray array];
    }
    return _relationArr;
}

// 当前视图控制器是否支持旋转
- (BOOL)shouldAutorotate
{
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.groupNumber = 1;
    [self requestData];
    [self customNavigationItem];
    [self.view addSubview: self.tableView];
    //[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"IntroduceTableViewCell" bundle:nil] forCellReuseIdentifier:@"IntroduceCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RelationMovieCell" bundle:nil] forCellReuseIdentifier:@"RelationMovieCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar lt_reset];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)customNavigationItem{
    // 获取视图控制器的UINavigationItem
    UINavigationItem * naviItem = self.navigationItem;
    
    UIImage * leftImage = [UIImage imageNamed:@"navigationbar_icon_back"];
    UIBarButtonItem * leftBarItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemClicked:)];
    leftBarItem.tintColor = [UIColor whiteColor];
    naviItem.leftBarButtonItem = leftBarItem;
    
    //    UIImage * rightImage = [UIImage imageNamed:@""];
    //    UIBarButtonItem * rightBarItem = [[UIBarButtonItem alloc] initWithImage:rightImage style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClicked:)];
    //    rightBarItem.tintColor = [UIColor lightGrayColor];
    //    naviItem.rightBarButtonItem = rightBarItem;
    _bigImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
    _bigImageView.clipsToBounds=YES;
    _bigImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    _headView=[[CreatorTableViewHeader alloc]init];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
   
    _iconImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    _iconImageView.center=CGPointMake(_bigImageView.center.x, _bigImageView.center.y);
    _iconImageView.clipsToBounds=YES;
    _iconImageView.layer.cornerRadius = 40;
    _iconImageView.layer.borderWidth = 2;
    _iconImageView.layer.borderColor = [UIColor brownColor].CGColor;
    _iconImageView.contentMode=UIViewContentModeScaleAspectFill;
    
    

    [_headView layoutWithTableView:self.tableView andBackGroundView:_bigImageView andIconImageView:_iconImageView];
    
}

- (void)leftBarButtonItemClicked:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
    UIColor * color = [UIColor blackColor];
    [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:1]];
}

-(void)viewDidLayoutSubviews
{
    [_headView resizeView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_headView scrollViewDidScroll:scrollView];
    
    if ([scrollView isEqual:_tableView]) {

        UIColor * color = [UIColor blackColor];
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY > 20) {
            CGFloat alpha = MIN(1, 1 - ((20 + 100 - offsetY) / 100));
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
        } else {
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
        }
    }
}

#pragma mark - UITableViewDatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.groupNumber;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

//组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.groupNumber == 2) {
        if (section == 0) {
            return 0.1;
        }
        else{
            return 10;
        }
    }else{
        return 0.1;
    }
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.groupNumber == 2) {
      if (indexPath.section == 0) {
          
         IntroduceTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"IntroduceCell"];
          
            tableView.estimatedRowHeight = 200;
            tableView.rowHeight = UITableViewAutomaticDimension;
            cell.introduceText = self.desc;
        
        return cell;
    }
    else{
        RelationMovieCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RelationMovieCell"];
      
        if (self.relationArr.count != 0) {
            tableView.rowHeight = 230;
            if (_allCount == self.relationArr.count) {
                cell.relationMovieArr = self.relationArr;
                cell.delegate = self;
                cell.title = @"代表作品";
                cell.numbers = [NSString stringWithFormat:@"%ld部相关电影",self.relationArr.count];
            }
        }else{
            tableView.rowHeight = 0;
          }
        
        return cell;
        
     }
    }else{
        RelationMovieCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RelationMovieCell"];
        if (self.relationArr.count != 0) {
            tableView.rowHeight = 230;
            if (_allCount == self.relationArr.count) {
                cell.relationMovieArr = self.relationArr;
                cell.delegate = self;
                cell.title = @"代表作品";
                cell.numbers = [NSString stringWithFormat:@"%ld部相关电影",self.relationArr.count];
            }
        }else{
            tableView.rowHeight = 0;
        }
        
        return cell;

    }
    
}

- (void)requestData{
    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeGradient];
    
    NSMutableDictionary *dict = @{}.mutableCopy;
    //dict[@"count"] = @"20";
    dict[@"artist_id"] = self.creatorID;
    
    [AFHTTPSessionManager requestWithType:AFHTTPSessionManagerRequestTypePOST URLString:MV_ACTOR parmaeters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        //[SVProgressHUD dismiss];
        //NSLog(@"respons  = %@",responseObject);
        AFHTTPRequestOperationManager *manager    = [AFHTTPRequestOperationManager manager];
        
        // 设置超时时间
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 10.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        self.name = responseObject[@"data"][@"profile_info"][@"name"];
        self.picUrl = responseObject[@"data"][@"profile_info"][@"avatar_large"];
        self.desc = responseObject[@"data"][@"profile_info"][@"desc"];
        
        NSNumber *number = responseObject[@"data"][@"profile_film"][@"count"];
        _allCount = [number intValue];
        
        if (self.desc.length != 0) {
            self.groupNumber = 2;
        }else{
            self.groupNumber = 1;
        }
        
        if (_allCount%20 != 0) {
            self.maxPage = [number intValue]/20 + 1;
        }else{
            self.maxPage = [number intValue]/20;
        }
        
        [self requestPic];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self renewUI];

        });
        

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error = %@",[error localizedDescription]);
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
}

//更新UI
- (void)renewUI{
    //[_bigImageView sd_setImageWithURL:[NSURL URLWithString:self.picUrl]];
    [_iconImageView sd_setImageWithURL:[NSURL URLWithString:self.picUrl]placeholderImage:[UIImage imageNamed:@"profile_Head_gray"]];
    [_bigImageView sd_setImageWithURL:[NSURL URLWithString:self.picUrl] placeholderImage:[UIImage imageNamed:@"profile_Head_gray"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        // 20 左右 R  模糊图片
        [_bigImageView setImageToBlur:_bigImageView.image blurRadius:21 completionBlock:nil];
    }];
    
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    _nameLabel.center = CGPointMake(_bigImageView.center.x, _bigImageView.center.y+60);
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.font = [UIFont systemFontOfSize:15];
    [_tableView addSubview:_nameLabel];
    _nameLabel.text = self.name;
    
}

- (void)requestPic{
    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeGradient];
    
    //循环请求数据,直到最后一组数据请求下来
    for (int i = 1; i <= self.maxPage; i++) {
        
    NSMutableDictionary *dict = @{}.mutableCopy;
    dict[@"count"] = @"20";
    dict[@"artist_id"] = self.creatorID;
    dict[@"page"] = [NSString stringWithFormat:@"%d",i];
    
    
    [AFHTTPSessionManager requestWithType:AFHTTPSessionManagerRequestTypePOST URLString:MV_ACTOR_MOVIE parmaeters:dict success:^(NSURLSessionDataTask *task, id responseObject) {

        NSArray * profile_filmArr = responseObject[@"data"][@"profile_film"];
        NSArray * relationModelArr = [RelationInfoModel mj_objectArrayWithKeyValuesArray:profile_filmArr];
       // NSLog(@"%ld",relationModelArr.count);
        
        for (RelationInfoModel * model in relationModelArr) {
            [self.relationArr addObject:model];
        }
        //NSLog(@"=====%ld",self.relationArr.count);
        
        if (_allCount == self.relationArr.count) {
            
        [SVProgressHUD showSuccessWithStatus:@"加载完成"];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
          });
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error = %@",[error localizedDescription]);
    }];
        
    }
}

#pragma mark - ClickRelationrCellDelegate
-(void)choseRelationInfoTerm:(NSInteger)num andPageID:(NSString *)pageid andCellNumber:(NSInteger)cellNumber
{
    if (num == 989) {
        return;
    }else{
    // 取出对应的模型数据
    RelationInfoModel * model = self.relationArr[num];
    MovieDetailViewController * MDVC = [[MovieDetailViewController alloc]init];
    MDVC.filmId = model.film_id;
    [self.navigationController pushViewController:MDVC animated:YES];
    }
}



@end
